﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BLL;
using System.Configuration;
using System.Collections;
using Model;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.IO.Compression;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace Sales
{
    public partial class MemberManagement : Form
    {

        private static MemberManagement memberManagement = null;
        public SysConfig config;
        public static string config_dir = Application.StartupPath + "/config";
        public static string config_file = config_dir + "/config.xml";
        public Common2 common = new Common2();

        public static MemberManagement CreateInstance()
        {
            if (null == memberManagement)
            {
                memberManagement = new MemberManagement();
            }
            return memberManagement;
        }


        public MemberManagement()
        {
            config = Common2.GetConfig( );//获取相关配置属性
            InitializeComponent();
            MiddleModule.eventSend += new Send(MiddleModule_eventSend);
            comBindData();

            this.ctxtBirthday.Value = DateTime.Now.AddYears(-26);
        }

        #region 页面属性

        /// <summary>
        /// 密码
        /// </summary>
        public string PassWord
        {
            get;
            set;

        }

        /// <summary>
        /// 店面编号 
        /// </summary>
        public string Dmbh
        {
            set;
            get;
        }
        /// <summary>
        /// 店面名称
        /// </summary>
        public string Dmmc
        {
            set;
            get;
        }

        /// <summary>
        /// 营业员
        /// </summary>
        public string Yyy
        {
            set;
            get;
        }

        #endregion


        private void MemberManagement_Load(object sender, EventArgs e)
        {

        }
        private void comBindData()
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("name");
            DataRow dr = dt.NewRow();
            dr["id"] = "0";
            dr["name"] = "正常";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["id"] = "1";
            dr["name"] = "补卡";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["id"] = "2";
            dr["name"] = "挂失";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["id"] = "3";
            dr["name"] = "注销";
            dt.Rows.Add(dr);


            this.comStatus.DataSource = dt;
            this.comStatus.ValueMember = "name";
            this.comStatus.DisplayMember = "name";
            this.comStatus.SelectedIndex = 0;
        }

        void MiddleModule_eventSend(object sender, object receiver, object msg)
        {
            //frmMain frmMain = sender as frmMain;
            //MemberList memberList = sender as MemberList;
            //数据来源 main页面
            if (memberManagement.ToString() == receiver.ToString())
            {
                MemberInfo model = JsonConvert.DeserializeObject<MemberInfo>(msg.ToString());
                if (model != null)
                {
                    this.txtKh.Text = model.Hykh;
                    this.ctxtDmbh.Text = model.Dmbh;
                    this.ctxtDmmc.Text = model.Dmmc;

                    Dmmc = model.Dmmc;
                    Dmbh = model.Dmbh;
                    Yyy = model.Yyymc;
                    if (model.Hykh !=null && model.Hykh != "")
                        SetMemberInfo(model.Hykh);
                }
            }
        }


        private void SetMemberInfo(string hykh)
        {
            HykblHBLL hykblhBLL = new HykblHBLL(config.WebApi);
            string strWhere = " kh='" + hykh + "'";

            //调用WebApi 接口
            hykblH_Entity entity1 = hykblhBLL.GetHykblHModelByWebApi(hykh, Dmbh);

 
            if (entity1 != null)
            {
                this.ctxtKhmc.Text = entity1.khmc;// dt.Rows[0]["khmc"].ToString();
                this.ctxtHyzk.Text = entity1.hyzk.ToString();// dt.Rows[0]["hyzk"].ToString();
                this.ctxtPassword.Text = entity1.mm;// dt.Rows[0]["mm"].ToString();
                this.ctxtAddress.Text = entity1.dz;// dt.Rows[0]["dz"].ToString();
                this.ctxtSfz.Text = entity1.sfz;// dt.Rows[0]["sfz"].ToString();
                this.ctxtPhone.Text = entity1.dh;// dt.Rows[0]["dh"].ToString();
                this.ctxtBz.Text = entity1.bz;// dt.Rows[0]["bz"].ToString();
                this.ctxtBirthday.Text = entity1.sr.ToString();// dt.Rows[0]["sr"].ToString();

                this.ctxtZjxfje.Text = entity1.zjxfjf.ToString();// dt.Rows[0]["zjxfjf"].ToString();
                this.ctxtZjxfsj.Text = entity1.zjxfsj.ToString();// dt.Rows[0]["zjxfsj"].ToString();
                this.ctxtXfzjf.Text = entity1.xfzjf.ToString();// dt.Rows[0]["xfzjf"].ToString();
                this.ctxtJfye.Text = entity1.jfye.ToString();// dt.Rows[0]["jfye"].ToString();

                PassWord = entity1.mm;// dt.Rows[0]["mm"].ToString();

                string _hykzt = entity1.hykzt;
                if (_hykzt == "正常")
                {
                    this.comStatus.SelectedIndex = 0;
                }
                else if (_hykzt == "补卡")
                {
                    this.comStatus.SelectedIndex = 1;
                }
                else if (_hykzt == "挂失")
                {
                    this.comStatus.SelectedIndex = 2;
                }
                else if (_hykzt == "注销")
                {
                    this.comStatus.SelectedIndex = 3;
                }
            }
            else
            {
                this.ctxtKhmc.Text = "";


                this.ctxtAddress.Text = "";
                this.ctxtSfz.Text = "";
                this.ctxtPhone.Text = "";
                this.ctxtBz.Text = "";
                this.ctxtBirthday.Text = "";

                this.ctxtZjxfje.Text = "";
                this.ctxtZjxfsj.Text = "";
                this.ctxtXfzjf.Text = "";
                this.ctxtJfye.Text = "";


            }


        }

        private void ctxtCzje_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '-')
            {
                e.Handled = true;
            }
        }


        private void gbtnSave_Click(object sender, EventArgs e)
        {
            //保存
            HykblHBLL hykblHBLL = new HykblHBLL(config.WebApi);
            List<string> sqlList = new List<string>();

            //HykblHModel

            if (this.comStatus.SelectedValue.ToString() != "")
            {
                string sfz = this.ctxtSfz.Text;
                string czje = this.ctxtCzje.Text;
                if (sfz !="" &&(!Regex.IsMatch(sfz, @"^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$", RegexOptions.IgnoreCase)))
                {
                    MessageBox.Show("请输入正确的身份证号码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;

                }

                hykblH_Entity hykblHModel = GetHykblHModel();
                if (ValidationHelper.IsFloat(czje))
                {
                    hykblHModel.hykye = decimal.Parse(this.ctxtCzje.Text);
                }
                else
                {
                    MessageBox.Show("充值金额不允许为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
             
                int status = hykblHBLL.HykAddByWebApi(hykblHModel);

                if (status > 0)
                {
                    MessageBox.Show("保存成功！");
                }
                else
                {
                    MessageBox.Show("保存失败！,网络问题");
                }
            }
            else
            {
                MessageBox.Show("请选择会员卡状态！");
            }
        }



        private hykblH_Entity GetHykblHModel()
        {
            hykblH_Entity model = new hykblH_Entity();

            LogHelper.m_CreateErrorLogTxt("单步调试", "1", "步骤:1  : GetHykblHModel 方法中 开始部分");

            string kh = this.txtKh.Text.Trim();
            model.kh = kh;


            string khmc = this.ctxtKhmc.Text.Trim();
            model.khmc = khmc;

            decimal hyzk = 0;

            if (this.ctxtHyzk.Text != "")
            {
                hyzk = decimal.Parse(this.ctxtHyzk.Text.Trim());
            }
            model.hyzk = hyzk;
            string passWord = "";

            passWord = this.ctxtPassword.Text.Trim();
            LogHelper.m_CreateErrorLogTxt("单步调试", "1", "步骤:2  : GetHykblHModel 方法中 开始部分");

            model.mm = passWord;

            model.khmc = this.ctxtKhmc.Text;

            string address = this.ctxtAddress.Text;
            model.dz = address;

            string sfz = this.ctxtSfz.Text;





            model.sfz = sfz;
            string phone = this.ctxtPhone.Text;
            model.dh = phone;
            string memberStatus = this.comStatus.SelectedValue.ToString();
            model.hykzt = memberStatus;
            string birthday = this.ctxtBirthday.Text;
            if (birthday != "")
            {
                if (birthday.IndexOf("星") > -1)
                {
                    model.sr = Convert.ToDateTime(birthday.Substring(0, birthday.IndexOf("星")));

                }
                else
                {
                    model.sr = Convert.ToDateTime(birthday);
                }



            }


            string bz = this.ctxtBz.Text;
            model.bz = bz;


            if (this.ctxtJfye.Text != "")
            {
                model.jfye = decimal.Parse(this.ctxtJfye.Text.Trim());
            }
            decimal czje = 0;
            if (this.ctxtCzje.Text != "")
            {
                czje = decimal.Parse(this.ctxtCzje.Text.Trim());


                if (model.jfye.ToString() != "")
                {
                    model.jfye = model.jfye;
                }

            }

            model.dmbh = Dmbh;
            model.dmmc = Dmmc;
            //   model.hykzt = this.comStatus.SelectedValue.ToString();
            model.sj = DateTime.Now;
            model.rq = DateTime.Now;

            model.djyh = Yyy;
            model.djsj = DateTime.Now;
            model.xgyh = Yyy;
            model.xgsj = DateTime.Now;


            model.UploadStatus = 0;
            return model;
        }

        #region 序列化 反序列化


        ///序列化转化为二进制数组的DataSet
        public byte[] GetDataSetSurrogateZipBYtes(DataSet DS)
        {
            DataSetSurrogate dss = new DataSetSurrogate(DS);
            ///二进制方式方式序列化

            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            ser.Serialize(ms, dss);
            byte[] buffer = ms.ToArray();
            ///调用压缩方法

            byte[] Zipbuffer = Compress(buffer);
            return Zipbuffer;
        }
        ///压缩二进制文件
        private byte[] Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            Stream zipStream = null;
            zipStream = new GZipStream(ms, CompressionMode.Compress, true);

            ///从指定的字节数组中将压缩的字节写入基础流

            zipStream.Write(data, 0, data.Length);
            zipStream.Close();
            ms.Position = 0;
            byte[] Compressed_Data = new byte[ms.Length];
            ms.Read(Compressed_Data, 0, int.Parse(ms.Length.ToString()));
            return Compressed_Data;
        }




        ///将压缩后的二进制数组解压

        public static byte[] Decompress(byte[] data)
        {      ///data参数为压缩后的二进制数组
            try
            {
                MemoryStream ms = new MemoryStream(data);
                Stream zipStream = null;
                zipStream = new GZipStream(ms, CompressionMode.Decompress);
                byte[] dc_data = null;
                dc_data = EtractBytesFormStream(zipStream, data.Length);
                return dc_data;

                ///返回解压后的二进制数组
            }
            catch
            {
                return null;
            }
        }


        public static byte[] EtractBytesFormStream(Stream zipStream, int dataBlock)
        {
            try
            {
                byte[] data = null;
                int totalBytesRead = 0;
                while (true)
                {
                    Array.Resize(ref data, totalBytesRead + dataBlock + 1);
                    int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    totalBytesRead += bytesRead;
                }
                Array.Resize(ref data, totalBytesRead);
                return data;
            }
            catch
            {
                return null;
            }
        }


        /// 将二进制文件反序列化后转化为DataSet

        public DataSet GetDatasetFromByte(byte[] ZipByte)
        {
            byte[] buffer = Decompress(ZipByte);
            BinaryFormatter ser = new BinaryFormatter();
            DataSetSurrogate dss;
            dss = (DataSetSurrogate)ser.Deserialize(new MemoryStream(buffer));
            DataSet DS = dss.ConvertToDataSet();
            return DS;

        }



        /// <summary>
        /// 序列化 HykblH
        /// </summary>
        /// <param name="xskdhModel"></param>
        /// <returns></returns>
        public string SerializeHykblH(HykblHModel hykblHModel)
        {
            //// 创建 BinaryFormatter 对象，用于序列化 EmployeeEntity 类型的对象
            BinaryFormatter formatter = new BinaryFormatter();
            // 将 EmployeeEntity 对象序列化为名为“xskdH.dat”的二进制文件
            FileStream stream = File.Create("MyxskdH.dat");
            formatter.Serialize(stream, hykblHModel);

            byte[] bytes = new byte[stream.Length];
            stream.Position = 0; // 这句不能少
            stream.Read(bytes, 0, (int)stream.Length);

            // Base64String
            string result = Convert.ToBase64String(bytes);

            stream.Close();

            return result;
        }
        /// <summary>
        /// 反序列化 HykblH
        /// </summary>
        /// <param name="strXskdH"></param>
        /// <returns></returns>
        public HykblHModel DeserializeHykblH(string strHykblH)
        {
            byte[] bytes = Convert.FromBase64String(strHykblH); // str 就是上一代码的 result
            HykblHModel result = null;
            using (Stream stream = new MemoryStream())
            {
                stream.Write(bytes, 0, bytes.Length);

                stream.Position = 0; // 这句不能少
                BinaryFormatter formatter = new BinaryFormatter();
                result = (HykblHModel)formatter.Deserialize(stream); // 这里的 result 是 MyObject 类型

                stream.Close();
            }
            return result;
        }




        /// 序列化DataTable
        /// </summary>
        /// <param name="pDt">包含数据的DataTable</param>
        /// <returns>序列化的DataTable</returns>
        public static string SerializeDataTableXml(DataTable pDt, string pdtname)
        {
            // 序列化DataTable
            pDt.TableName = pdtname;
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
            serializer.Serialize(writer, pDt);
            writer.Close();
            return sb.ToString();
        }


        /// <summary>
        /// 反序列化DataTable
        /// </summary>
        /// <param name="pXml">序列化的DataTable</param>
        /// <returns>DataTable</returns>
        public static DataTable DeserializeDataTable(string pXml)
        {

            StringReader strReader = new StringReader(pXml);
            XmlReader xmlReader = XmlReader.Create(strReader);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

            DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
            return dt;
        }
        #endregion

        private void ctxtHyzk_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '-')
            {
                e.Handled = true;
            }
        }

        private void MemberManagement_FormClosed(object sender, FormClosedEventArgs e)
        {
            //frmMain main = new frmMain();
            //string msg = ctxtCzje.Text;
            //MiddleModule.SendMessage(this, main, msg);
        }

        private void ctxtHyzk_Leave(object sender, EventArgs e)
        {
            string value = this.ctxtHyzk.Text;
            if (value != "")
            {
                if (float.Parse(value) > 10 || float.Parse(value) <= 0)
                {
                    MessageBox.Show("折扣不能大于10，且不能小于等于 0");
                    this.ctxtHyzk.Text = "1";
                }
            }
        }
    }
}
